const { result } = require('@hapi/joi/lib/base')
const db = require('../db/index')

//获取文章分类列表数据
exports.getArtcateCates = (req, res) => {
  const sql = 'select * from ev_artcate_cate where is_delete=0 order by id asc'
  db.query(sql, (err, result) => {
    if (err) return res.cc(err)

    res.send({
      status: 0,
      message: '获取文章分类列表数据成功!',
      data: result
    })
  })
}

//新增分章分类
exports.addArtcateCates = (req, res) => {
  const sql = 'select * from ev_artcate_cate where name=? or alias=?'
  db.query(sql, [req.body.name, req.body.alias], (err, result) => {
    if (err) return res.cc(err)
    if (result.length === 2) return res.cc('分类名称与别名被占用!')
    if (result.length === 1 && result[0].name === req.body.name && result[0].alias === req.body.alias) return res.cc('分类名称与别名被占用!')
    if (result.length === 1 && result[0].name === req.body.name) return res.cc('分类名称被占用!')
    if (result.length === 1 && result[0].alias === req.body.alias) return res.cc('分类别名被占用!')

    const addsql = 'insert into ev_artcate_cate set ?'
    db.query(addsql, req.body, (err, result) => {
      if (err) res.cc(err)
      if (result.affectedRows !== 1) return res.cc('新增文章分类失败!')
      res.cc('新增成功!')
    })
  })
}

//删除分类文章
exports.deleteArtcateCates = (req, res) => {
  const sql = 'update ev_artcate_cate set is_delete=1 where id=? '
  db.query(sql, req.params.id, (err, result) => {
    if (err) return res.cc(err)
    if (result.affectedRows !== 1) return res.cc('删除失败')
    res.cc('删除成功', 0)
  })
}

//根据id获取文章分类
exports.getArtcateById = (req, res) => {
  const sql = 'select * from ev_artcate_cate where id=? and is_delete=0'
  db.query(sql, req.params.id, (err, result) => {
    if (err) return res.cc(err)
    if (result.length !== 1) return res.cc('查询文章分类数据失败')
    res.send({
      status: 0,
      message: '查询文章分类数据成功',
      data: result[0]
    })
  })
}

//根据id更新文章分类数据
exports.updateArtcateCate = (req, res) => {
  const sql = 'select * from ev_artcate_cate where id<>? and (name=? or alias=?)'
  db.query(sql, [req.body.id, req.body.name, req.body.alias], (err, result) => {
    if (err) return res.cc(err)
    if (result.length === 2) return res.cc('分类名称与别名被占用!')
    if (result.length === 1 && result[0].name === req.body.name && result[0].alias === req.body.alias) return res.cc('分类名称与别名被占用')
    if (result.length === 1 && result[0].name === req.body.name) return res.cc('分类名称被占用')
    if (result.length === 1 && result[0].alias === req.body.alias) return res.cc('分类别名被占用')

    const updateSql = 'update ev_artcate_cate set ? where id=? and is_delete=0'
    db.query(updateSql, [req.body, req.body.id], (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows !== 1) return res.cc('更新文章分类失败')
      res.cc('更新文章分类成功')
    })
  })

}